#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <uchardet/uchardet.h>

#define BOLD_GRAY "\033[1;90m"
#define RED "\033[0;31m"
#define WHITE "\033[0;37m"
#define RESET "\033[0m"

// Размер буфера для чтения
#define BUFFER_SIZE 4096

int module_06_run(const char *filename) {
    char log_msg[1024];

    FILE *file = fopen(filename, "rb");
    if (!file) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library uchardet: " RED "File type not recognized: %s" RESET, strerror(errno));
        printf("%s\n", log_msg);
        return 1;
    }

    unsigned char *buffer = malloc(BUFFER_SIZE);
    if (!buffer) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library uchardet: " RED "Memory allocation failed" RESET);
        printf("%s\n", log_msg);
        fclose(file);
        return 1;
    }

    size_t read_bytes = fread(buffer, 1, BUFFER_SIZE, file);
    fclose(file);

    if (read_bytes == 0) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library uchardet: " RED "File type not recognized: Empty file" RESET);
        printf("%s\n", log_msg);
        free(buffer);
        return 1;
    }

    uchardet_t handle = uchardet_new();
    if (!handle) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library uchardet: " RED "Memory allocation failed" RESET);
        printf("%s\n", log_msg);
        free(buffer);
        return 1;
    }

    if (uchardet_handle_data(handle, (const char *)buffer, read_bytes) != 0) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library uchardet: " RED "Error processing data" RESET);
        printf("%s\n", log_msg);
        uchardet_delete(handle);
        free(buffer);
        return 1;
    }

    uchardet_data_end(handle);
    const char *encoding = uchardet_get_charset(handle);
    if (encoding && strlen(encoding) > 0) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library uchardet: " WHITE "Detected encoding: %s" RESET, encoding);
    } else {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library uchardet: " RED "Unknown encoding" RESET);
    }
    printf("%s\n", log_msg);
    uchardet_delete(handle);
    free(buffer);
    return 0;
}
